package com.swsc.xapp.baseContent;

import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.os.Build;


import com.swsc.xapp.service.CustomForegroundService;
import com.swsc.xapp.utils.GlobalExceptionHandler;
import com.swsc.xapp.utils.SystemUtils;
import com.swsc.xapp.utils.ToastUtils;


import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class MyApplication extends Application {

    private String TAG = "MyApplication";
    public static String deviceName="";

    @Override
    public void onCreate() {
        super.onCreate();

        // 启动服务 2022-07-21 13:56
        startService();
        // 全局异常处理
        GlobalExceptionHandler.getInstance().init(this);
//        ToastUtils.getToast();
    }

    /**
     * 启动服务
     */
    private void startService() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            //安卓引导用户设置APP运行后台保活3.安卓8.0以上开启为前台服务
            startForegroundService(new Intent(this, CustomForegroundService.class));
        } else {
            startService(new Intent(this, CustomForegroundService.class));
        }
    }

    @Override
    public void onLowMemory() {
        super.onLowMemory();
    }

    @Override
    protected void attachBaseContext(Context base) {
        if ("OPPO".equals(SystemUtils.getDeviceBrand())) {
            fixOppoAssetManagerBug();
        }
        super.attachBaseContext(base);
    }

    //oppo手机修改rom，会导致assetmanager超时
    // https://blog.csdn.net/zlmrche/article/details/81365204
    //http://www.courtier.cc/2017/04/28/%E5%85%B3%E4%BA%8Etimeoutexception%E8%BF%99%E4%BB%B6%E5%B0%8F%E4%BA%8B/
    private void fixOppoAssetManagerBug() {
        try {
            Class clazz = Class.forName("java.lang.Daemons$FinalizerWatchdogDaemon");
            Method stopMethod = clazz.getSuperclass().getDeclaredMethod("stop");
            stopMethod.setAccessible(true);

            Field field = clazz.getDeclaredField("INSTANCE");
            field.setAccessible(true);

            stopMethod.invoke(field.get(null));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
